import React, { Component } from 'react';
import { Label } from '@folio/stripes/components';
import PropTypes from 'prop-types';
import TetherComponent from 'react-tether';

import uniqueId from 'lodash/uniqueId';

import upload from './ImageUpload.css';

const propTypes = {
  autoFocus: PropTypes.bool,
  disabled: PropTypes.bool,
  id: PropTypes.string,
  input: PropTypes.object,
  label: PropTypes.node,
  locale: PropTypes.string,
  meta: PropTypes.object,
  onChange: PropTypes.func,
  readOnly: PropTypes.bool,
  required: PropTypes.bool,
  screenReaderMessage: PropTypes.string,
  showTimepicker: PropTypes.bool,
  tether: PropTypes.object,
  timeZone: PropTypes.string,
  value: PropTypes.string,
  buttonName: PropTypes.string,
  imageUploadHttpInvoke: PropTypes.object
};
function getUrlBase64(url) {
  return new Promise((resolve, reject) => {
    let canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    let img = new Image();
    img.crossOrigin = 'Anonymous'; // 开启img的“跨域”模式
    img.src = url;
    img.onload = function () {
      canvas.height = img.height;
      canvas.width = img.width;
      ctx.drawImage(img, 0, 0, img.width, img.height); // 参数可自定义
      const dataURL = canvas.toDataURL('image/jpeg', 1); // 获取Base64编码
      resolve(dataURL);
      canvas = null; // 清除canvas元素
      img = null; // 清除img元素
    };
    img.onerror = function () {
      reject(new Error('Could not load image at ' + url));
    };
  });
}

class ImageUpload extends Component {
  constructor(props) {
    super(props);
    this.textfield = React.createRef();
    this.container = null;

    this.state = {
      uploadHistory: [],
      uri: '/party/uploads/imageFile',
      size: props.size || 20,
      files: props.files || [],
      multiple: props.multiple || false,
      progress: [], // 默认一次最多上传20张
      imageId: '',
      uploadFlag: true,
      timeString: '',
      srMessage: ''
    };

    if (props.id) {
      this.testId = props.id;
    } else {
      this.testId = uniqueId('updateImage-');
    }
  }

  // 取消拖拽时鼠标经过样式
  handleDragHover = e => {
    e.stopPropagation();
    e.preventDefault();
  };

  handleChange = event => {
    this.setState({ progress: [] });
    event.preventDefault();
    const target = event.target;
    let files = target.files;

    const count = this.state.multiple ? files.length : 1;
    for (let i = 0; i < count; i++) {
      files[i].thumb = URL.createObjectURL(files[i]);
    }
    // convert to array
    files = Array.prototype.slice.call(files, 0);
    files = files.filter(file => {
      return /image/i.test(file.type);
    });

    this.handleUpload(files[0]);
  };

  getImage = (imageId, flag) => {
    if (this.state.imageId === '') {
      const query = `(id = "${imageId}")`;
      this.props.imageUploadHttpInvoke.GET({ params: { query } }).then(res => {
        if (res.imageGroup) {
          if (res.imageGroup.length > 0) {
            const img = res.imageGroup[0];
            const content = img.content;
            const f = {};
            f.type = 'image/jpeg';
            f.thumb = content;
            const files = [f];
            this.setState({
              files,
              imageId,
              uploadFlag: flag
            });
          }
        }
      });
      // const okapi = this.props.stripes.okapi;
      // const url = okapi.url + "/activity/get_upload_image/" + imageId;
      //
      // fetch(url, {
      //   method: "get",
      //   headers: {
      //     "X-Okapi-Tenant": okapi.tenant,
      //     "X-Okapi-Token": okapi.token
      //   }
      // })
      //   .then(response => response.blob())
      //   .then(res => {
      //     const src = URL.createObjectURL(res);
      //     const f = {};
      //     f.type = "image/jpeg";
      //     f.thumb = src;
      //     const files = [f];
      //     this.setState({
      //       files,
      //       imageId,
      //       uploadFlag: flag
      //     });
      //   });
    }
  };

  // 关闭了上传功能
  invokeImages = imageId => {
    this.getImage(imageId, false);
  };

  componentDidMount() {}

  handleUpload = file => {
    const _this = this;
    const okapi = _this.props.stripes.okapi;
    const okapiUrl = okapi.url + this.state.uri;
    // const formData = new FormData();
    // formData.append("file", file);
    // formData.append("fileName", "file");
    const jpeg = 'jpeg';
    const png = 'png';
    const jpg = 'jpg';
    const gif = 'gif';
    const maxsize = 1048576;
    if (file) {
      if (file.size > maxsize) {
        alert('上传的图片不能超过1mb，请调整之后再上传');
        return false;
      }
      const type = file.type;
      const fileType = type.split('/')[1];

      if (
        fileType !== jpeg &&
        fileType !== png &&
        fileType !== jpg &&
        fileType !== gif
      ) {
        alert(
          `上传的图片格式只能是${jpeg},${png},${jpg},${gif}，请调整之后再上传`
        );
        return false;
      }

      const fileName = `${new Date().getTime()}.${fileType}`;
      getUrlBase64(file.thumb).then(base64 => {
        const formData = {
          content: base64,
          name: fileName
        };
        this.props.imageUploadHttpInvoke.POST(formData).then(res => {
          const tmp = [];
          tmp.push(file);
          _this.setState({ imageId: res.id, files: tmp });
          if (this.props.input) {
            this.props.input.onChange(res.id);
            if (this.props.onChange) {
              this.props.onChange(e, res.id);
            }
          } else if (this.props.onChange) {
            this.props.onChange(e, res.id);
          }
        });
        //     fetch(okapiUrl, {
        //         method: "post",
        //         headers: {
        //             "X-Okapi-Tenant": okapi.tenant,
        //             "X-Okapi-Token": okapi.token,
        //             "Content-Type": 'multipart/form-data'
        //         },
        //         body: formData
        //     })
        //         .then(response => response.json())
        //         .then(res => {
        //             const tmp = [];
        //             tmp.push(file);
        //             _this.setState({ imageId: res.data, files: tmp });
        //             if (this.props.input) {
        //                 this.props.input.onChange(res.data);
        //                 if (this.props.onChange) {
        //                     this.props.onChange(e, res.data);
        //                 }
        //             } else if (this.props.onChange) {
        //                 this.props.onChange(e, res.data);
        //             }
        //         });
      });
    } else {
      alert('上传的图片找不到，请重新上传');
      return false;
    }
  };

  _renderPreview = () => {
    if (this.state.files) {
      return this.state.files.map((item, idx) => {
        return (
          <div className="upload-append-list">
            <img src={item.thumb} className={upload.uploadImage} />
          </div>
        );
      });
    } else {
      return null;
    }
  };

  render() {
    const { readOnly, disabled, input, labelName, requiredFlag } = this.props;
    if (!!input && !!input.value) {
      this.getImage(input.value, true);
    }
    const errorElement = this.props.meta.error ? (
      <div style={{ color: '#900' }}>{this.props.meta.error}</div>
    ) : null;

    return (
      <TetherComponent>
        <div
          style={{ position: 'relative', width: '100%' }}
          ref={ref => {
            this.container = ref;
          }}
        >
          <div
            aria-live="assertive"
            aria-relevant="additions"
            className={upload.srOnly}
            ref={ref => {
              this.srSpace = ref;
            }}
          >
            <div>{this.state.srMessage}</div>
          </div>
          <Label
            htmlFor="updateImage-1"
            className="label---HZh8H"
            style={{
              display: 'flex',
              alignItems: 'center',
              fontSize: '1rem',
              lineHeight: '1.5',
              marginBottom: '0.25rem',
              color: '#000'
            }}
          >
            {labelName || '活动图片'}
            {requiredFlag && (
              <span className={upload.imageUploadRequired}>*</span>
            )}
          </Label>
          <div className={upload.ryUploadBox}>
            <div className={upload.uploadMain}>
              {this.state.uploadFlag ? (
                <div ref="dragBox" className={upload.uploadDragArea}>
                  <input
                    onChange={v => this.handleChange(v)}
                    type="file"
                    size={this.state.size}
                    name="fileSelect"
                    accept="image/*"
                    id={this.testId}
                    multiple={this.state.multiple}
                    className={upload.uploadImageBgInput}
                    required={!this.state.uploadFlag}
                  />

                  <div className={upload.uploadPreview}>
                    {this._renderPreview()}
                  </div>
                </div>
              ) : (
                <div className={upload.uploadPreview}>
                  {this._renderPreview()}
                </div>
              )}
              {errorElement}
            </div>
          </div>
        </div>
      </TetherComponent>
    );
  }
}

ImageUpload.propTypes = propTypes;

export default ImageUpload;
